<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .box {
        position: fixed;
        top: 50%;
        left: 50%;
        z-index: 9999;
        transform: translate(-50%, -50%);

        cursor: move;
        width: 300px;
        height: 300px;
        background-color: pink;
    }
</style>
<body>

<div class="box" id="box"></div>

<script>

    var box = document.querySelector('#box');

    box.addEventListener('mousemove', function (e) {
        // 1.首先得到鼠标在文档页面中的坐标 e.pageX e.pageY
        var x = e.pageX;
        var y = e.pageY;

        // 2.其次得到在盒子在页面中的距离 (box.offsetLeft, box.offsetTop)
        var left = this.offsetLeft;
        var top = this.offsetTop;

        this.innerHTML = `(${x - left}, ${y - top})`;
        console.log(` (${x - left}, ${y - top})`)
    })

    // 4.拖拽
    // (1) 当我们鼠标按下(mousedown), 就获取的鼠标在盒子内坐标
    box.addEventListener('mousedown', function (e) {
        // 鼠标在盒子内坐标
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;

        // (2) 鼠标移动的时候, 把鼠标在页面的坐标, 减去鼠标在盒子内的坐标就是模态框的left和top值
        document.addEventListener('mousemove', move)

        function move(evt) {
            // bug点 this.style.style.left -> Uncaught TypeError: Cannot set property 'left' of undefined
            // console.log(this)       // #document  这个this指向的是this, 回调函数中的函数指向的document
            box.style.left = evt.pageX - x + 'px';
            box.style.top = evt.pageY - y + 'px';
        }

        // (3) 鼠标弹起, 就让鼠标移动事件解除
        document.addEventListener('mouseup', function () {
            document.removeEventListener('mousemove', move);
        })
    })
</script>
</body>
</html>
